package com.servlet;

import com.pojo.LocalUpload;
import com.pojo.Response;
import com.service.UploadHead;
import com.util.JsonUtil;
import com.util.ResponseUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
@WebServlet(value = "/uploadServlet")
public class UploadServlet extends BaseServlet{
    /*
       上传头像
     */
    protected void upload_head(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, FileUploadException {
        System.out.println("[info]开始上传文件");
        req.setCharacterEncoding("UTF-8");
//        1.先判断上传的数据是否多段数据（只有多段数据，才是文件上传的）
        //创建FileItemFacotry工厂实现类
        FileItemFactory fileItemFactory=new DiskFileItemFactory();
        //创建用于解析上传数据的工具类ServletFileUpload类
        ServletFileUpload servletFileUpload=new ServletFileUpload(fileItemFactory);
        String userid= (String) req.getSession().getAttribute("userid");
        req.getSession().removeAttribute("userid");
        try {
            //解析上传的数据，得到每一个表单项FileItem
            List<FileItem> list=servletFileUpload.parseRequest(req);
            for(FileItem fileItem:list)
            {
                if(fileItem.isFormField()) {//普通表单项
                    System.out.println("表单项的name属性值:" + fileItem.getFieldName());
                    //参数UTF-8解决乱码问题
                    System.out.println("表单项的value属性值：" + fileItem.getString("UTF-8"));
                }
                else{
                    //上传的文件
                    System.out.println("[info]上传文件成功");
                    //上传头像到数据库
                    UploadHead.upload(req,"../warehouse/"+userid+"_"+fileItem.getName());

                    fileItem.write(new File("D:\\Blog-Website\\web\\warehouse\\"+userid+"_"+fileItem.getName()));
                    resp.getWriter().write(JsonUtil.toJson(new Response(110,"上传成功","../warehouse/"+userid+"_"+fileItem.getName())));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        http://localhost:8080/warehouse/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png
    }

    /**
     *本地上传图片
     */
    protected void local_upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, FileUploadException{
        System.out.println("[info]本地上传");
        req.setCharacterEncoding("UTF-8");
//        1.先判断上传的数据是否多段数据（只有多段数据，才是文件上传的）
        //创建FileItemFacotry工厂实现类
        FileItemFactory fileItemFactory=new DiskFileItemFactory();
        //创建用于解析上传数据的工具类ServletFileUpload类
        ServletFileUpload servletFileUpload=new ServletFileUpload(fileItemFactory);
        try {
            //解析上传的数据，得到每一个表单项FileItem
            List<FileItem> list=servletFileUpload.parseRequest(req);
            for(FileItem fileItem:list)
            {
                if(fileItem.isFormField()) {//普通表单项
                    System.out.println("表单项的name属性值:" + fileItem.getFieldName());
                    //参数UTF-8解决乱码问题
                    System.out.println("表单项的value属性值：" + fileItem.getString("UTF-8"));
                }
                else{
                    //上传的文件
                    System.out.println("[info]本地上传文件成功");

                    fileItem.write(new File("D:\\Blog-Website\\web\\warehouse\\"+fileItem.getName()));
                    String url="http://localhost:8080/warehouse/"+fileItem.getName();
                    resp.getWriter().write(JsonUtil.toJson(new LocalUpload(1,"上传成功",url)));;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 暂时保存用户id
     */
    protected void save_id(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
           req.getSession().setAttribute("userid",req.getParameter("userid"));
           resp.getWriter().write(ResponseUtil.SUCCESS("",null));
    }
}
